package com.woniuxy.school.gateway.fifter;

import cn.hutool.json.JSONUtil;
import com.woniuxy.commons.core.model.Result;
import com.woniuxy.school.gateway.conig.FilterProperties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

/**
 * * createResource("/order/v2/api-docs","订单服务"),
 * * createResource("/product/v2/api-docs","商品服务"),
 * * createResource("/cinema/v2/api-docs","影厅服务"),
 * * createResource("/user/v2/api-docs","用户服务")
 */
@Component
public class AuthenticationFilter implements GlobalFilter {
    // 定义需要放行的地址列表
    @Autowired
    private FilterProperties filterProperties;  //需要放行的资源统一到配置文件
    private AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        System.out.println("执行登录认证");
//        //获取请求地址
//        String path = exchange.getRequest().getURI().getPath();
//        List<String> allows = filterProperties.getAllows();
//        if (allows != null && allows.size() > 0) {
//            for (String allow : allows) {
//                if (matcher.match(path, allow)) return chain.filter(exchange); //放行不需要验证的请求
//            }
//        }
//
//        List<String> tokens = exchange.getRequest().getHeaders().get("movie-token");
//
//        if (tokens == null || tokens.size() <= 0) {
//            return unAuthor(exchange);
//        }
//        //判断是用户端还是管理端的认证
////        if (path.endsWith(".adm")) {
////            //表示管理端
////            try {
////                JwtUtil.parseAdminToken(tokens.get(0));
////            } catch (Exception e) {
////                return unAuthor(exchange);
////            }
////        } else {
////            //表示用户端
////            try {
////                JwtUtil.parseUserToken(tokens.get(0));
////            } catch (Exception e) {
////                return unAuthor(exchange);
////            }
////        }
//         try {
//             JwtUtil.parseUserToken(tokens.get(0));
//         } catch (Exception e) {
//             return unAuthor(exchange);
//         }
//        //通过
        return chain.filter(exchange);
    }

    /**
     * 用户未认证通过
     *
     * @param exchange
     * @return
     */
    private Mono<Void> unAuthor(ServerWebExchange exchange) {
        Result<Boolean> result = Result.getResult(Boolean.class)
                .setCode(401).setMessage("未登录");
        exchange.getResponse().getHeaders()
                .setContentType(MediaType.APPLICATION_JSON);
        String json = JSONUtil.parse(result).toString();
        //响应
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> exchange.getResponse().bufferFactory().wrap(json.getBytes())));
    }

//    @Bean
//    public GlobalFilter corsFilter() {
//        return (exchange, chain) -> {
//            exchange.getResponse().getHeaders().add("Access-Control-Allow-Origin", "*");
//            exchange.getResponse().getHeaders().add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
//            exchange.getResponse().getHeaders().add("Access-Control-Allow-Headers", "*");
//            if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) {
//                exchange.getResponse().setStatusCode(HttpStatus.OK);
//                return Mono.empty();
//            }
//            return chain.filter(exchange);
//        };
//    }

}
